package com.wifipositioner.widget;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;

import com.wifipositioner.Globals;
import com.wifipositioner.R;
import com.wifipositioner.activity.FileChooserActivity;

public class FileNameChooserPopup extends PopupWindow {

	private Button btn_cancel;
	private Button btn_ok;
	private EditText et_input;

	public FileNameChooserPopup(View contentView, int width, int height,
			boolean focusable) {
		super(contentView, width, height, focusable);
		btn_cancel = (Button) contentView
				.findViewById(R.id.filenamepopup_btn_cancel);
		btn_ok = (Button) contentView.findViewById(R.id.filenamepopup_btn_ok);
		et_input = (EditText) contentView
				.findViewById(R.id.filenamepopup_edittext_filename);
		registerHandlers();
	}

	private void registerHandlers() {
		btn_cancel.setOnClickListener(cancelBtnOnClickListener);
		btn_ok.setOnClickListener(okBtnOnClickListener);

	}

	private OnClickListener cancelBtnOnClickListener = new OnClickListener() {
		public void onClick(View v) {
			dismiss();
		}
	};
	private OnClickListener okBtnOnClickListener = new OnClickListener() {
		File sdCardRoot = Environment.getExternalStorageDirectory();

		public void onClick(View v) {

			try {

				File file = new File(sdCardRoot, Globals.mapPath
						+ et_input.getText().toString());
				FileOutputStream fos = new FileOutputStream(file);

				fos.write("".getBytes());
				fos.close();
				dismiss();
				getContentView().forceLayout();
				((FileChooserActivity) getContentView().getContext())
						.newReferenceMapCreated(et_input.getText()
								.toString());

			} catch (FileNotFoundException e) {
				File newDir = new File(sdCardRoot + File.separator +Globals.mapPath);
				newDir.mkdirs();
				onClick(v);
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	};
}
